package com.example.demo2025011501

import android.os.SystemClock
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
Day1->1
suspend:暂停执行当前协程,并保存局部变量
挂起函数   只能协程体内获其他挂起函数内
retrofit可以省略调度函数
withContext(Dispatchers.IO){
userApi.getUser()
}
可以改为userApi.getUser()
 /**
     * 获取网络数据
     * GlobalScope:顶级协程
     */
    fun getNetDatas() {
        GlobalScope.launch(Dispatchers.Main) {//指定主线程
            logMsg("准备获取数据:${Thread.currentThread().name}")
            val result = getNetDatasSuspend()
            tv_main_content.text=result
            logMsg("获取的数据:${Thread.currentThread().name}，${result}")
        }
    }

    /**
     * 标记子协程在子线程中
     */
    suspend fun getNetDatasSuspend(): String {
        return withContext(Dispatchers.IO) {//指定IO线程
            SystemClock.sleep(5000)
            logMsg("getNetDatasSuspend的线程:${Thread.currentThread().name}")
            "hello world"
        }
    }

Day1->2
    ///理解挂起
    fun guaqi(){
        GlobalScope.launch(Dispatchers.Main) {
            delay(10*1000)//不影响主线程
            logMsg("挂起,${Thread.currentThread().name}")
        }
    }

Day1->3
    ///创建协程并挂起并恢复
    fun createSuspend(){
        val createCoroutine = suspend {
            5
        }.createCoroutine(object : Continuation<Int> {
            override val context: CoroutineContext
                get() = EmptyCoroutineContext

            /**
             * 协程实际还是回调
             */
            override fun resumeWith(result: Result<Int>) {
                logMsg("resumeWith:${result}")
            }

        })
        createCoroutine.resume(Unit)
    }

Day1->4协程取消会抛异常,如果不try则不会抛异常,并且不会走下去
val mainScope= MainScope()
fun testMainScope(){
mainScope.launch {
try {

delay(10000)
}catch (e:Exception)
{
//kotlinx.coroutines.JobCancellationException: Job was cancelled; job=SupervisorJobImpl{Cancelling}@cddb3f8
e.printStackTrace()
}
}
}

 Day1->5直接委托对象:MyActivity,CoroutineScope by MainScope() {


 */